package com.example.mahao_final.UI

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mahao_final.R
import com.example.mahao_final.adapter.BlogAdapter
import com.example.mahao_final.database.BlogDatabase
import com.example.mahao_final.entity.Blog
import kotlinx.coroutines.launch

class BlogFragment : Fragment(R.layout.fragment_blog) {

    private lateinit var rvBlogList: RecyclerView
    private lateinit var blogAdapter: BlogAdapter
    private val blogDao by lazy { BlogDatabase.getDatabase(requireContext()).blogDao() }

    // 定义 Handler 和 Runnable
    private val handler = android.os.Handler()
    private val updateRunnable = object : Runnable {
        override fun run() {
            loadBlogs()  // 加载数据
            handler.postDelayed(this, 1000)  // 每秒重新执行
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        rvBlogList = view.findViewById(R.id.rv_blog_list)

        // 设置 RecyclerView
        rvBlogList.layoutManager = LinearLayoutManager(requireContext())

        // 创建适配器，并设置点击回调
        blogAdapter = BlogAdapter(emptyList()) { blog ->
            // 点击事件回调，启动新的 Activity 显示博客的详细信息
            showBlogDetails(blog)
        }

        rvBlogList.adapter = blogAdapter

        // 启动定时任务，每秒获取一次数据
        handler.post(updateRunnable)
    }

    // 停止定时任务，避免内存泄漏
    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(updateRunnable)  // 停止定时任务
    }

    private fun loadBlogs() {
        // 使用协程从数据库中加载博客数据
        lifecycleScope.launch {
            val blogs = blogDao.getAllBlogs()  // 获取所有博客数据
            blogAdapter.updateList(blogs)  // 更新 RecyclerView 数据
        }
    }

    // 处理点击博客跳转到博客详情的逻辑
    private fun showBlogDetails(blog: Blog) {
        val intent = Intent(requireContext(), BlogDetailActivity::class.java)
        intent.putExtra("BLOG_ID", blog.id)  // 传递博客的 ID
        startActivity(intent)
    }
}
